<template>
  <div class="login">
    <div class="login-bg"></div>
    <div class="login-content">
      <div style="text-align: center;font-size: 22px;margin:0 0 30px">欢迎登录{{appName}}</div>
      <Form :model="loginInfo">
        <FormItem prop="loginName">
          <Input type="text" v-model="loginInfo.loginName" placeholder="登录名" size="large"
                 prefix="ios-contact"/>
        </FormItem>
        <FormItem prop="pwd">
          <Input type="password" v-model="loginInfo.pwd" placeholder="密码" size="large" prefix="md-key"
                 @on-enter="loginIn()"/>
        </FormItem>
        <FormItem prop="rememberPwd">
          <Checkbox v-model="rememberPwd" size="large">记住密码</Checkbox>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="loginIn()" size="large" style="width:260px">登录</Button>
        </FormItem>
      </Form>
      <a href="javascript:void(0)" style="margin-bottom: 10px">忘记密码?</a>
    </div>
  </div>
</template>

<script>
  import {prelogin, login, validateToken} from '@/api/sys/user.js'
  import sha256 from 'sha256'
  import {Base64} from 'js-base64'

  export default {
    name: "index",
    data() {
      return {
        appName:config.appName,
        rememberPwd: false,
        loginInfo: {
          loginName: '',
          pwd: ''
        }
      }
    },
    created() {
      //读缓存判断是否已登录，且token有效，如果有效，跳转到控制台
      let token = localStorage.getItem('token')
      let userId = localStorage.getItem('userId')
      if (this.validateToken(userId, token)) {
        return
      }
      //如果缓存失效，从cookie中取用户名密码并初始化
      this.rememberPwd = this.$cookies.get('rememberPwd') == 'true'
      this.loginInfo.loginName = this.$cookies.get('loginName')
      this.loginInfo.pwd = this.$cookies.get('pwd')
    },
    methods: {
      loginIn() {
        const self = this
        let params = {
          loginName: self.loginInfo.loginName,
        }
        prelogin(params)
          .then((response) => {
            let pkgOut = response.data
            let userInf = pkgOut.data
            let pwdA = self.loginInfo.pwd + '|' + userInf.oldSalt
            let pwdB = self.loginInfo.pwd + '|' + userInf.newSalt
            for (let N = 0; N < userInf.hashTimes; N++) {
              pwdA = sha256(pwdA)
              pwdB = sha256(pwdB)
            }
            params.pwd = ''
            params.pwdA = Base64.encode(pwdA)
            params.pwdB = Base64.encode(pwdB)
            login(params)
              .then((responseEnd) => {
                let pkgOutEnd = responseEnd.data
                let loginInfo = pkgOutEnd.data
                localStorage.setItem('userId', loginInfo.id)
                localStorage.setItem('loginName', loginInfo.loginName)
                let token = loginInfo.token
                if (token != '' && token != null) {
                  localStorage.setItem('token', token)
                }
                let avatar = loginInfo.avatar;
                if (avatar != '' && avatar != null) {
                  localStorage.setItem('avatar', avatar)
                } else {
                  localStorage.setItem('avatar', '../../../static/images/avatar.jpg')
                }

                //是否保存用户名密码
                if (self.rememberPwd) {
                  self.$cookies.set('rememberPwd', self.rememberPwd)
                  self.$cookies.set('loginName', self.loginInfo.loginName)
                  self.$cookies.set('pwd', self.loginInfo.pwd)
                } else {
                  self.$cookies.remove('rememberPwd')
                  self.$cookies.remove('loginName')
                  self.$cookies.remove('pwd')
                }

                localStorage.removeItem('tabs')
                localStorage.removeItem('activeUrl')
                self.$router.push('/layout')
              })
              .catch(
                function (err) {
                  self.$Modal.error({
                    title: '错误信息',
                    content: err
                  })
                }
              )
          })
          .catch(
            function (err) {
              self.$Modal.error({
                title: '错误信息',
                content: err
              })
            }
          )
      },
      validateToken(userId, token) {
        const self = this
        if (userId == undefined || token == undefined || token == '') {
          return false
        }
        let params = {
          userId: userId,
          token: token
        }
        validateToken(params)
          .then((response) => {
            let pkgOut = response.data
            if (pkgOut.data) {
              self.$router.push('/layout')
            }
          })
          .catch((err) => {
            self.$Modal.error({
              title: '错误信息',
              content: err
            })
          })
      }
    }
  }
</script>

<style scoped>
  .login {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .login-content {
    position: relative;
    left: 40%;
    top: 150px;
    width: 300px;
    height: 550px;
    padding: 20px;
    background-color: #fff;
  }

  .login-bg {
    background: url('../../../static/images/login-bg.png') no-repeat;
    position: absolute;
    float: left;
    width: 100%;
    height: 100vh;
  }
</style>
